<template>
  <div :class="{file:true,selected:selected}" v-on="$listeners" @click="select">
    <div class="icon-ctn">
      <svg-icon :icon-class="iconClass" class="icon"/>
    </div>
    <textarea :style="{height:textareaHeight,width:textareaWidth}" class="name" v-if="edit" @blur="edit=false" v-model="data.name"></textarea>
    <label class="name" v-else @click="editFromLabel">{{data.name}}</label>
    <div class="name temp-label">{{data.name}}</div>
  </div>
</template>
<script>
  export default {
    name:'file',
    props:{
      data:Object
    },
    data(){
      return {
        selected:false,
        edit:false,
        textareaHeight:'auto',
        textareaWidth:'auto'
      }
    },
    computed:{
      iconClass(){
        let fileTypes = {
          folder:'folder',
          file:'file'
        }
        return fileTypes[this.data.type]
      }
    },
    watch:{
      edit(){
        if(this.edit){
          this.$nextTick(()=>{
            this.$el.querySelector('textarea').select();
            this.$el.querySelector('textarea').focus();
          })
        }
      },
      "data.name"(){
        this.$nextTick(()=>{
          this.setLabelSize();
        })
      }
    },
    mounted(){
      this.setLabelSize();
    },
    methods:{
      setLabelSize(){
        this.textareaHeight = this.$el.querySelector('.temp-label').offsetHeight+'px';
        this.textareaWidth = (this.$el.querySelector('.temp-label').offsetWidth+1)+'px';
      },
      select(){
        console.log(11);
        if(!this.selected){
          this.$emit('selected',this);
        }
        this.selected = true;
      },
      unSelect(){
        this.selected = false;
      },
      editFromLabel(){
        this.$nextTick(()=>{
          console.log(this.selected);
          if(this.selected){
            this.edit = true;
          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
.file{
  text-align: center;
  position:relative;
  .icon-ctn{
    width:4.5em;
    height:4.5em;
    line-height:4.5em;
    margin:0 auto;
    border-radius: 5px;
    .icon{
      font-size:3.5em;
      vertical-align: middle;
    }
  }
  .name{
    margin-top:4px;
    font-size:.8em;
    padding:2px 5px;
    border-radius: 5px;
    text-align: center;
    line-height:1.5em;
    box-sizing: border-box;
    word-break:break-all;
  }
  textarea{
    resize: none;
    border:0;
    // padding:0;
    max-width:100%;
    display:inline;
  }
  label.name{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-inline-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  div.name{
    max-height: 3em;
    position:absolute;
    visibility: hidden;
    max-width:100%;
  }
}
.file.selected{
  .icon-ctn{
    background-color: rgba(55, 51, 51);
  }
  label.name{
    background-color: rgb(22, 82, 177);
  }
}
</style>